﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ABCComputer.BLL;
using DTO;
using ABCComputer.App_Code;

namespace ABCComputer
{
    public partial class WebForm2 : System.Web.UI.Page
    {
        GioHang gh;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                gh = new GioHang();
                string action = Request.QueryString["action"];
                string masp = Request.QueryString["masp"];

                if (action != null)
                {
                    if (action.Equals("dathang"))
                    {
                        gh.themGioHang(masp);

                    }
                    else if (action.Equals("xoa"))
                    {
                        gh.xoaMotSanPhamKhoiGioHang(masp);
                    }

                }

                loadGridView();
            }
            
        }

        // load thông tin giỏ hàng
        public void loadGridView()
        {
            decimal thanhtien;
            decimal tongtien;
            List<GioHangDTO> lst = (List<GioHangDTO>)Session["GioHang"];
            gh = new GioHang();
            for (int i = 0; i < lst.Count; i++)
            {
                thanhtien = gh.thanhTien(i);
                lst[i].Thanhtien = thanhtien;
            }
            
            tongtien = gh.tongTien(lst);
            
            GVGioHang.DataSource = lst;
            GVGioHang.DataBind();

            if (GVGioHang.Rows.Count != 0)
            {
                Label lblTongTien = (Label)GVGioHang.FooterRow.Cells[5].FindControl("lbltongtien");
                lblTongTien.Text = String.Format("{0:0,0 vnđ}", tongtien);
            }
            else
            {
                btnCapNhat.Visible = false;
                btnMuaHang.Visible = false;
                btnTiepTucMuaHang.Visible = false;
                btnXoaGioHang.Visible = false;
            }
        }

        // cập nhật giỏ hàng
        protected void btnCapNhat_Click(object sender, EventArgs e)
        {
            
            for (int i = 0; i < GVGioHang.Rows.Count; i++)
            {
                GridViewRow gvrow = GVGioHang.Rows[i];
                int soluong = int.Parse(((TextBox) gvrow.Cells[3].FindControl("txtsoluong")).Text);
                string masp = ((Label) gvrow.Cells[1].FindControl("lblmasanpham")).Text;
                gh = new GioHang();
                gh.capNhatSoLuongSanPham(i, masp, soluong);
                
            }
            loadGridView();
        }

    }
}